package common

import (
	"context"
	"fmt"

	"gitee.com/lyuanbo/stock-trade/internal/pkg/stock/signal"
)

// Signal 注册信号, 监听数据
type Signal struct {
	CodeIds []string // 股票代码
	Periods []string // 周期
	Ctx     context.Context
}

func (s *Signal) SetCodeIds(codeIds []string) {
	s.CodeIds = codeIds
}

func (s *Signal) SetPeriods(periods []string) {
	s.Periods = periods
}

func (s *Signal) SetContext(ctx context.Context) {
	s.Ctx = ctx
}

func (s *Signal) Listen(topic string, fn func(codeId string)) {
	for _, codeId := range s.CodeIds {
		for _, period := range s.Periods {
			go func() {
				var channel chan struct{}
				signal.Register("strategy", codeId, fmt.Sprintf("%s_%s", topic, period), channel)

				// 监听数据
				for {
					select {
					case <-channel:
						// 处理数据
						fn(codeId)
					case <-s.Ctx.Done():
						return
					}
				}
			}()
		}
	}
}
